const { ethers } = require("hardhat");

/**
 * 与已部署的合约交互的脚本
 * 演示如何在真实网络上使用合约
 */
async function main() {
    console.log("🔗 与已部署的合约交互\n");
    
    // 合约地址（需要替换为实际部署的地址）
    const CONTRACT_ADDRESS = "0x5FbDB2315678afecb367f032d93F642f64180aa3"; // 示例地址
    
    // 获取网络信息
    const network = await ethers.provider.getNetwork();
    const [user] = await ethers.getSigners();
    
    console.log("📊 交互环境:");
    console.log(`网络: ${network.name} (${network.chainId})`);
    console.log(`用户地址: ${user.address}`);
    console.log(`合约地址: ${CONTRACT_ADDRESS}\n`);
    
    try {
        // 连接到已部署的合约
        const AuctionNFT = await ethers.getContractFactory("AuctionNFT");
        const contract = AuctionNFT.attach(CONTRACT_ADDRESS);
        
        console.log("🔍 查询合约信息:");
        
        // 基本信息查询
        const name = await contract.name();
        const symbol = await contract.symbol();
        const owner = await contract.owner();
        const totalSupply = await contract.getTotalSupply();
        const nextTokenId = await contract.getNextTokenId();
        
        console.log(`合约名称: ${name}`);
        console.log(`合约符号: ${symbol}`);
        console.log(`合约拥有者: ${owner}`);
        console.log(`总供应量: ${totalSupply}`);
        console.log(`下一个TokenId: ${nextTokenId}`);
        
        // 检查用户是否为合约拥有者
        const isOwner = user.address.toLowerCase() === owner.toLowerCase();
        console.log(`当前用户是否为拥有者: ${isOwner ? '是' : '否'}`);
        
        if (isOwner) {
            console.log("\n🎨 执行铸造操作:");
            
            // 铸造NFT
            const tokenURI = `https://example.com/metadata/${Date.now()}.json`;
            console.log(`正在铸造NFT，URI: ${tokenURI}`);
            
            const mintTx = await contract.mint(user.address, tokenURI);
            console.log(`交易已发送: ${mintTx.hash}`);
            console.log("等待交易确认...");
            
            const receipt = await mintTx.wait();
            console.log(`✅ 铸造成功! Gas使用: ${receipt.gasUsed}`);
            
            // 查询新铸造的NFT
            const newTokenId = await contract.getTotalSupply();
            const tokenOwner = await contract.ownerOf(newTokenId);
            const tokenURIResult = await contract.tokenURI(newTokenId);
            const creator = await contract.getCreator(newTokenId);
            
            console.log(`\n🎯 新NFT信息:`);
            console.log(`TokenId: ${newTokenId}`);
            console.log(`拥有者: ${tokenOwner}`);
            console.log(`创建者: ${creator}`);
            console.log(`TokenURI: ${tokenURIResult}`);
            
        } else {
            console.log("\n📖 只读操作（非拥有者）:");
            
            // 查询已存在的NFT（如果有的话）
            if (totalSupply > 0) {
                for (let i = 1; i <= Math.min(Number(totalSupply), 5); i++) {
                    try {
                        const tokenOwner = await contract.ownerOf(i);
                        const tokenURI = await contract.tokenURI(i);
                        const creator = await contract.getCreator(i);
                        
                        console.log(`\nNFT #${i}:`);
                        console.log(`  拥有者: ${tokenOwner}`);
                        console.log(`  创建者: ${creator}`);
                        console.log(`  URI: ${tokenURI}`);
                    } catch (error) {
                        console.log(`NFT #${i}: 不存在或查询失败`);
                    }
                }
            } else {
                console.log("暂无NFT可查询");
            }
        }
        
        // 监听事件（演示）
        console.log("\n👂 设置事件监听器:");
        console.log("监听NFT铸造事件...");
        
        contract.on("NFTMinted", (to, tokenId, tokenURI, creator, event) => {
            console.log(`\n🎉 检测到新的NFT铸造事件:`);
            console.log(`  接收者: ${to}`);
            console.log(`  TokenId: ${tokenId}`);
            console.log(`  URI: ${tokenURI}`);
            console.log(`  创建者: ${creator}`);
            console.log(`  交易哈希: ${event.log.transactionHash}`);
        });
        
        console.log("事件监听器已设置，将监听后续的铸造事件...");
        
    } catch (error) {
        console.error("❌ 交互失败:", error.message);
        
        if (error.message.includes("call revert exception")) {
            console.log("\n💡 可能的原因:");
            console.log("1. 合约地址不正确");
            console.log("2. 合约未部署到当前网络");
            console.log("3. 网络连接问题");
        }
    }
}

main()
    .then(() => {
        console.log("\n✅ 交互脚本执行完成");
        // 保持进程运行以监听事件
        console.log("按 Ctrl+C 退出事件监听...");
    })
    .catch((error) => {
        console.error("❌ 脚本执行失败:", error);
        process.exit(1);
    });